import re
from datetime import datetime

from models.model import House, Area, Facility, Order
from models.model import User
from ihome.mysql import get_db
from sqlalchemy.orm import Session
from utlis.realName import usercheck
from utlis.qiniuyun import qiniu_upload
from utlis.password import hash_password
from utlis.captcha.captcha import captcha
from utlis.aliyun_sms import send_sms_code
from fastapi.responses import JSONResponse
from utlis.password import verify_password
from fastapi import APIRouter, Request, Response, Depends
from utlis.baiduai import client
import random

router = APIRouter()


# 图片验证码
@router.get('/imagecode')
async def image_code(request: Request, cur: str = None):
	image_code_id = cur
	# 生成图片验证码
	text, image = captcha.generate_captcha()
	# 保存图片验证码
	# redis_conn = get_redis_connection('code')
	await request.app.state.redis.setex('img_%s' % image_code_id, 300, text)
	print(text)
	# 响应图片验证码
	return Response(content=image, media_type='image/jpeg')


# 发送短信验证码
@router.post('/sms')
async def sms_code(request: Request):
	data = await request.json()
	print(data)
	mobile = data.get('mobile')
	image_code_id = data.get('id')
	image_code = data.get('text')
	# 对前端传过来的数据进行校验
	if not all([mobile, image_code]):
		return {"errno": "400", "errmsg": "缺少参数"}
	if not re.match(r'^1[3-9]\d{9}$', str(mobile)):
		return {"errno": '4103', "errmsg": "手机号不合格"}
	redis_code = await request.app.state.redis.get('img_%s' % image_code_id)
	if not redis_code or redis_code.decode().lower() != image_code.lower():
		return {"errno": "4103", "errmsg": "图片验证码错误"}
	# 生成随机短信验证码
	code = random.randint(1000, 9999)
	# 短信验证码保存到redis
	await request.app.state.redis.setex(mobile, 300, code)
	# 阿里云发送手机验证码
	# send_sms_code(mobile, code)
	print(code)
	return {
		"errno": "0",
		"errmsg": "发送成功"
	}


# 注册
@router.post('/users')
async def register(request: Request, db: Session = Depends(get_db)):
	# 接收前端传过来的数据
	data = await request.json()
	mobile = data.get('mobile')
	phoneode = data.get('phonecode')
	password = data.get('password')
	# 校验前端传过来的数据
	if not all([mobile, phoneode, password]):
		return {"errno": "4002", "errmsg": "缺少参数"}
	if not re.match(r'^1[3-9]\d{9}$', str(mobile)):
		return {"errno": '4103', "errmsg": "手机号不合格"}
	try:
		# 对密码进行加密
		password = data.get('password')
		hashed_password = hash_password(password)
		user = User(
			username=mobile,
			mobile=mobile,
			password=hashed_password
		)
		db.add(user)
		db.commit()
	except Exception as e:
		print(e)
	return {
		"errno": "0",
		"errmsg": "注册成功"
	}


# 登录
@router.post('/session')
async def login_user(request: Request, db: Session = Depends(get_db)):
	# 获取前端传递过来的数据
	data = await request.json()
	mobile = data.get('mobile')
	password = data.get('password')
	# 校验前端传过来的数据
	if not all([mobile, password]):
		return {"errno": "4002", "errmsg": "缺少参数"}
	if not re.match(r'^1[3-9]\d{9}$', str(mobile)):
		return {"errno": '4103', "errmsg": "手机号不合格"}
	# 从数据库中把数据拿出来
	try:
		user = db.query(User).filter(User.mobile == mobile).first()
		if not user:
			return {"errno": "4104", "errmsg": "用户不存在"}
		if not verify_password(password, user.password):
			return {"errno": "4105", "errmsg": "密码错误"}

		resource = JSONResponse(content={"errno": "0", "errmsg": "登录成功"})
		resource.set_cookie(key="mobile", value=user.mobile, httponly=True)
		return resource
	except Exception as e:
		print(e)


# 判断是否登录
@router.get('/session')
async def check_login(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get("mobile")
	user = db.query(User).filter(User.mobile == mobile).first()
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	return {
		"errno": "0",
		"errmsg": "用户已登录",
		"data": {
			"name": user.username,
			"user_id": user.id,
		}
	}


# 退出登录
@router.delete('/session')
async def logout_user(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get("mobile")
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	resource = JSONResponse(content={"errno": "0", "errmsg": "登录成功"})
	resource.set_cookie(key="mobile", value='', httponly=False)
	return resource


# 个人中心
@router.get('/user')
async def user_info(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get("mobile")
	user = db.query(User).filter(User.mobile == mobile).first()
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	if not user.avatar:
		return {"errno": "4002", "errmsg": "用户未上传头像"}
	return {
		"data": {
			"avatar_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + user.avatar,
			# "create_time": user.create_tame,
			"mobile": mobile,
			"name": user.username,
			"user_id": user.id
		},
		"errmsg": "OK",
		"errno": "0"
	}


# 上传头像
@router.post('/user/avatar')
async def upload_avatar(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get("mobile")
	user = db.query(User).filter(User.mobile == mobile).first()
	data = await request.form()
	user_image = data.get('avatar')
	image_avatar = user_image.file.read()
	image = client.imageCensorUserDefined(image_avatar)
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	try:
		if image.get("conclusion") != '合规':
			return {'errno': '4103', 'errmsg': '图片不合规'}
		else:
			# 重置指针到文件开头
			user_image.file.seek(0)
			ret, info = qiniu_upload(user_image.file)
			if not info.status_code == 200:
				return {"errno": "4103", "errmsg": "参数错误"}
			user.avatar = ret['key']
			db.commit()
			return {
				"data": {
					"avatar_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + user.avatar,
				},
				"errno": "0",
				"errmsg": "头像上传成功"
			}
	except Exception as e:
		print('e')


# 修改用户名
@router.put('/user/name')
async def update_name(request: Request, db: Session = Depends(get_db)):
	data = await request.json()
	name = data.get('name')
	mobile = request.cookies.get("mobile")
	result = client.textCensorUserDefined(name)
	if result.get('conclusion') != "合规":
		user = db.query(User).filter(User.mobile == mobile).first()
		wname = random.randrange(0, 999999)
		user.username = "违规用户" + str(wname)
		db.commit()
		return {"errno": "4103", "errmsg": "用户名不合规"}
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	if not name:
		return {"errno": "4002", "errmsg": "用户名不能为空"}
	try:
		user = db.query(User).filter(User.mobile == mobile).first()
		user.username = name
		db.commit()
		return {
			"errno": "0",
			"errmsg": "修改成功"
		}
	except Exception as e:
		print(e)


# 用户实名认证
@router.post('/user/auth')
async def auth(request: Request, db: Session = Depends(get_db)):
	data = await request.json()
	real_name = data.get('real_name')
	id_card = data.get('id_card')
	aa = usercheck(real_name, id_card)

	if aa.get('respCode') != '0000':
		return {
			"errno": "4101",
			"errmsg": "身份证号错误"
		}
	try:
		mobile = request.cookies.get("mobile")
		user = db.query(User).filter(User.mobile == mobile).first()
		user.real_name = real_name
		user.id_card = id_card
		db.commit()
		return {
			"errno": "0",
			"errmsg": "实名认证成功"
		}
	except Exception as e:
		print(e)


# 获取实名认证信息
@router.get('/user/auth')
async def auth(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get("mobile")
	user = db.query(User).filter(User.mobile == mobile).first()
	return {
		"errno": '0',
		"data": {
			"real_name": user.real_name if user.real_name else '',
			"id_card": user.id_card if user.id_card else ''
		}
	}


# 城区列表
@router.get('/areas')
async def areas(request: Request, db: Session = Depends(get_db)):
	data = db.query(Area).all()
	areas = []
	for i in data:
		areas.append({
			"aid": i.id,
			"aname": i.name
		})
	return {
		"errmsg": "获取成功",
		"errno": "0",
		"data": areas
	}


# 房源列表
@router.get('/user/houses')
async def houses(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get("mobile")
	user = db.query(User).filter(User.mobile == mobile).first()
	user_id = user.id
	house_all = db.query(House).filter(House.user_id == user_id).all()
	houses = []
	for house in house_all:
		houses.append({
			"address": house.address,
			"area_name": house.area_id,
			"ctime": house.create_time,
			"house_id": house.id,
			"img_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + house.index_image_url,
			"order_count": house.order_count,
			"price": house.price,
			"room_count": house.room_count,
			"title": house.title,
			"user_avatar": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + user.avatar
		})

	return {
		"data": {
			"houses": houses
		},
		"errmsg": "ok",
		"errno": "0"
	}


# 发布房源
@router.post('/houses')
async def publish_house(request: Request, db: Session = Depends(get_db)):
	data = await request.json()
	mobile = request.cookies.get('mobile')
	user = db.query(User).filter(User.mobile == mobile).first()
	list1 = []
	f1 = data.get("facility")
	for i in f1:
		f2 = db.query(Facility).filter(Facility.id == i).first()
		list1.append(f2)
	data['facility'] = list1
	data['user_id'] = user.id
	house = House(**data)
	db.add(house)
	db.commit()
	return {
		"errno": "0",
		"errmsg": "发布成功",
		"data": {
			"house_id": house.id
		}
	}


from fastapi import File


# 上传房源图片
@router.post('/houses/{house_id}/images')
async def publish_house(request: Request, house_id: int, db: Session = Depends(get_db)):
	data = await request.form()
	house_image = data.get('house_image')
	house = db.query(House).filter(House.id == house_id).first()
	image = client.imageCensorUserDefined(house_image.file.read())
	mobile = request.cookies.get('mobile')
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	try:
		if image.get("conclusion") != '合规':
			return {'errno': '4103', 'errmsg': '图片不合规'}
		else:
			# 重置指针到文件开头
			house_image.file.seek(0)
			ret, info = qiniu_upload(house_image.file)
			if not info.status_code == 200:
				return {"errno": "4103", "errmsg": "参数错误"}
			house.index_image_url = ret['key']
			db.commit()
			return {
				"data": {
					"avatar_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + house.index_image_url,
				},
				"errno": "0",
				"errmsg": "房源图片上传成功"
			}
	except Exception as e:
		print(e)


# 首页房屋展示
@router.get('/houses/index')
async def index(request: Request, db: Session = Depends(get_db)):
	houses = db.query(House).filter(House.index_house == 1).all()
	list1 = []
	for i in houses:
		list1.append({
			"house_id": i.id,
			"img_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.index_image_url,
			"title": i.title
		})
	return {
		"data": list1,
		"errmsg": "OK",
		"errno": "0"
	}


# 房屋数据搜索
@router.get('/houses')
async def houses(request: Request, db: Session = Depends(get_db)):
	data = request.query_params
	aid = data.get('aid')
	sk = data.get('sk')
	houses = db.query(House)

	if aid:
		houses = houses.filter(House.area_id == aid)
	if sk:
		if sk == 'price-inc':
			houses = houses.order_by('price')
		elif sk == 'price-des':
			houses = houses.order_by('-price')
		else:
			houses = houses.order_by('order_count')
	houses = houses.all()

	list1 = []
	for i in houses:
		list1.append({
			"address": i.address,
			"area_name": i.area.name,
			"ctime": i.create_time,
			"house_id": i.id,
			"img_url": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.index_image_url,
			"order_count": i.order_count,
			"price": i.price,
			"room_count": i.room_count,
			"title": i.title,
			"user_avatar": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.user.avatar
		})

	dict1 = {
		"data": {
			"houses": list1
		},
		"errmsg": "ok",
		"errno": "0"
	}
	return dict1


# 房屋详情页面
@router.get('/houses/{house_id}')
async def get_house(request: Request, house_id: int, db: Session = Depends(get_db)):
	house = db.query(House).filter(House.id == house_id).first()
	user_id = house.user_id
	user = db.query(User).filter(User.id == user_id).first()
	if not house:
		return {"errno": "4001", "errmsg": "房屋不存在"}
	list1 = []
	if house.facility:
		for i in house.facility:
			list1.append(i.id)
	list2 = []
	if house.urls:
		for i in house.urls:
			list2.append('http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.url)
	order = db.query(Order).filter(House.id == house_id).first()
	list3 = []
	list3.append({
		"comment": order.comment,
		"ctime": order.create_time,
		"user_name": user.username
	})
	dict1 = {

		"acreage": house.acreage,
		"address": house.address,
		"beds": house.beds,
		"capacity": house.capacity,
		"comments": list3,
		"deposit": house.deposit,
		"facilities": list1,
		"hid": house.id,
		"img_urls": list2,
		"max_days": house.max_days,
		"min_days": house.min_days,
		"price": house.price,
		"room_count": house.room_count,
		"title": house.title,
		"unit": house.unit,
		"user_avatar": 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + user.avatar,
		"user_id": user.id,
		"user_name": user.username
	}

	mobile2 = request.cookies.get("mobile")
	user2 = db.query(User).filter(User.mobile == mobile2).first()

	return {
		"data": {
			"house": dict1,
			"user_id": -1 if not user2 else user2.id
		},
		"errmsg": "OK",
		"errno": "0"
	}


# 添加订单
@router.post('/orders')
async def create_order(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get('mobile')
	user = db.query(User).filter(User.mobile == mobile).first()
	data = await request.json()
	house_id = data.get('house_id')
	start_date = data.get('start_date')
	end_date = data.get('end_date')
	house = db.query(House).filter(House.id == house_id).first()
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	if not data:
		return {"errno": "4002", "errmsg": "无参数"}

	house_price = house.price
	end = datetime.strptime(end_date, "%Y-%m-%d")
	start = datetime.strptime(start_date, "%Y-%m-%d")

	days = (end - start).days
	amount = house_price * days

	order = Order(
		house_id=house_id,
		begin_date=start,
		days=days,
		end_date=end,
		amount=amount,
		user=user,
		house_price=house_price,
		status=0
	)
	db.add(order)
	db.commit()
	return {
		"data": {
			"order_id": order.id
		},
		"errno": "0",
		"errmsg": "下单成功"
	}


# # 获取订单列表
# @router.get('/orders')
# async def get_orders(request: Request,db: Session = Depends(get_db)):
# 	mobile = request.cookies.get('mobile')
# 	user = db.query(User).filter(User.mobile == mobile).first()
# 	role = request.query_params
# 	list1 = []
# 	if role == 'custom':
# 		orders = db.query(Order).filter(Order.user_id == user.id)
# 		list2 = []
# 		orders = db.query(Order)
# 		for i in orders:
# 			if i.house.index_image_url:
# 				str1 = 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.house.index_image_url
# 			else:
# 				str1 = ''
# 			list2.append({
# 				"amount": i.amount,
# 				"comment": i.comment,
# 				"ctime": i.create_time,
# 				"days": i.days,
# 				"end_date": i.end_date,
# 				"img_url": str1,
# 				"order_id": i.id,
# 				"start_date": i.begin_date,
# 				"status": i.status_enum.name,
# 				"title": i.house.title
# 			})
# 			return {
# 				"data": {
# 					"orders": list2
# 				},
# 				"errmsg": "OK",
# 				"errno": "0"
# 			}
# 	elif role == 'landlord':
# 		users = db.query(House).filter(House.user_id == user.id)
# 		for i in users:
# 			list1.append(i.id)
# 		orders = Order.objects.filter(house_id__in=list1)


@router.get('/orders')
async def get_orders(request: Request, db: Session = Depends(get_db)):
	mobile = request.cookies.get('mobile')
	user = db.query(User).filter(User.mobile == mobile).first()
	role = request.query_params.get('role')
	list1 = []

	if role == 'custom':
		orders = db.query(Order).filter(Order.user_id == user.id)
		list2 = []
		for i in orders:
			if i.house.index_image_url:
				str1 = 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.house.index_image_url
			else:
				str1 = ''
			list2.append({
				"amount": i.amount,
				"comment": i.comment,
				"ctime": i.create_time,
				"days": i.days,
				"end_date": i.end_date,
				"img_url": str1,
				"order_id": i.id,
				"start_date": i.begin_date,
				"status": i.status_enum.name,
				"title": i.house.title
			})

		return {
			"data": {
				"orders": list2
			},
			"errmsg": "OK",
			"errno": "0"
		}

	elif role == 'landlord':
		houses = db.query(House).filter(House.user_id == user.id)
		for house in houses:
			list1.append(house.id)
		orders = db.query(Order).filter(Order.house_id.in_(list1))
		list2 = []
		for i in orders:
			if i.house.index_image_url:
				str1 = 'http://s5yc6o2h0.hd-bkt.clouddn.com/' + i.house.index_image_url
			else:
				str1 = ''
			list2.append({
				"amount": i.amount,
				"comment": i.comment,
				"ctime": i.create_time,
				"days": i.days,
				"end_date": i.end_date,
				"img_url": str1,
				"order_id": i.id,
				"start_date": i.begin_date,
				"status": i.status_enum.name,
				"title": i.house.title
			})

		return {
			"data": {
				"orders": list2
			},
			"errmsg": "OK",
			"errno": "0"
		}


# 接单和拒单
@router.put('/orders/{order_id}/status')
async def update_status(request: Request, order_id: int, db: Session = Depends(get_db)):
	data = await request.json()
	action = data.get('action')
	reject = data.get('reject')

	if action == 'accept':
		order = db.query(Order).filter(Order.id == order_id).first()
		if order.status != 0:
			return {"errno": "4103", "errmsg": "状态不是待接单"}
		else:
			order.status = 3
			db.commit()
	elif action == 'reject':
		order = db.query(Order).filter(Order.id == order_id).first()
		order.status = 6
		order.comment = reject
		db.commit()
		return {"errno": "0", "errmsg": "拒单成功"}
	else:
		return {"errno": "4103", "errmsg": "请正确输入"}


# 发表评论
@router.put('/orders/{order_id}/comment')
async def update_comment(request: Request, order_id: int, db: Session = Depends(get_db)):
	data = await request.json()
	order = db.query(Order).filter(Order.id == order_id).first()
	mobile = data.get('mobile')
	if not mobile:
		return {"errno": "4101", "errmsg": "用户未登录"}
	if not order:
		return {"errno": "4101", "errmsg": "没有该订单"}
	order.comment = data.get('comment')
	db.commit()
	return {
		"errno": "0",
		"errmsg": "评论成功"
	}
